/**
 * @author harry
 * @date 2022/3/6/21:21
 */

package com.serviceOrchestration.advice;

import com.serviceOrchestration.exception.LoginException;
import com.serviceOrchestration.exception.NotFoundException;
import com.serviceOrchestration.exception.PurchaseException;
import com.serviceOrchestration.exception.ServerException;
import com.serviceOrchestration.pojo.ReturnData;
import com.serviceOrchestration.util.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class RestExceptionHandler {

    /** 服务器内部错误返回500 */
    @ExceptionHandler(ServerException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ReturnData<?> serverException(Exception e) {
        log.error("server error: {}", e.getMessage());
        return ReturnData.error(StatusCode.SERVER_ERROR);
    }

    /** 参数缺失或有误返回400 */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.OK)
    public ReturnData<?> paramException(Exception e) {
        String message = e.getMessage();
        log.error("params error: " + message);
        return ReturnData.error(StatusCode.PARAM_ERROR, message);
    }

    @ExceptionHandler(NotFoundException.class)
    @ResponseStatus(HttpStatus.OK)
    public ReturnData<?> notFoundException(Exception e) {
        String message = e.getMessage();
        log.error("not found: {}", message);
        return ReturnData.error(StatusCode.NOT_FOUND, message);
    }

    @ExceptionHandler(LoginException.class)
    @ResponseStatus(HttpStatus.OK)
    public ReturnData<?> unauthorizedException(Exception e) {
        String message = e.getMessage();
        log.error("unauthorized: {}", message);
        return ReturnData.error(StatusCode.UNAUTHORIZED, message);
    }

    @ExceptionHandler(PurchaseException.class)
    @ResponseStatus(HttpStatus.OK)
    public ReturnData<?> purchaseException(Exception e) {
        String message = e.getMessage();
        log.error("purchase failure: {}", message);
        return ReturnData.error(StatusCode.NOT_ACCEPTABLE, message);
    }

    @ExceptionHandler(Throwable.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ReturnData<?> otherException(Throwable e) {
        e.printStackTrace();
        return ReturnData.error(500, e.getMessage());
    }
}
